<?php

namespace app\common\middleware;

use app\common\model\AdminMenu;
use app\common\service\UserService;
use app\utils\Auth;
use ReflectionClass;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AdminAccessAuth implements MiddlewareInterface
{
    
    public function process(Request $request, callable $handler): Response
    { 
        
        if (!str_contains($request->path(), '/admin')) {
            return \response(file_get_contents(base_path('public/admin/index.html')));
        }
        
        $controller = $request->controller;
        $action = $request->action;
        $authAccess = $this->canAccess($controller, $action);
        if ($authAccess['code'] != 1) {
            // 无权限情况，如果是
            if ($authAccess['code'] === 10001) {
                return json(['code' => 10001, 'msg' => '未登录', 'data' => []]);
            }
            return json(['code' => $authAccess['code'], 'msg' => $authAccess['msg'], 'data' => []]);
        } else {
            return $request->method() == 'OPTIONS' ? response('') : $handler($request);
        }
    }
    
    public function canAccess(string $controller, string $action)
    {
        
        $reflectionClass = new ReflectionClass($controller);
        $properties = $reflectionClass->getDefaultProperties();
        $noNeedAuth = $properties['noNeedAuth'] ?? [];
        $noNeedLogin = $properties['noNeedLogin'] ?? [];
        $className = str_replace('Controller', '', $reflectionClass->getShortName());
        $namespace = $reflectionClass->getNamespaceName();
        
        // 不需要登录
        if (in_array($action, $noNeedLogin)) {
            return ['code' => 1, 'msg' => '登录鉴权通过'];
        }
        
        $userId = UserService::getId();
        
        if (!$userId) {
            return ['code' => 10001, 'msg' => '请登录'];
        }
        
        // 超级管理员
        if ($userId === 1) {
            return ['code' => 1, 'msg' => '超级管理员，无需鉴权'];
        }
        
        // 不需要鉴权
        if (in_array($action, $noNeedAuth)) {
            return ['code' => 1, 'msg' => '无需鉴权通过'];
        }
        
        $rules = UserService::getRules($userId);
        
        if (empty($rules)) {
            return ['code' => 0, 'msg' => '管理员无角色'];
        }
        
        $list = array_map('strtolower', $rules);
        $menu = AdminMenu::getMenus();
        $statusAuth = true;
        $menuKey = '\\' . $namespace . '\\' . $className . '@' . $action;
        
        // 1.先用菜单path与角色的权限path比对，
        $menuIndex = arr2Search($menuKey, $menu, 'key');
        if ($menuIndex >= 0) {
            $hasRole = array_search(strtolower($menu[$menuIndex]['path']), $list);
            if (empty($hasRole)) {
                $statusAuth = false;
            }
        }
        
        if (empty($statusAuth)) {
            return ['code' => 0, 'msg' => $menuKey . '必须鉴权'];
        }
        
        return ['code' => 1, 'msg' => '角色拥有该权限'];
    }
    
}